package com.cs342.uwosh.cloudycontacts.tasks.network;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.cs342.uwosh.cloudycontacts.RestClient;

import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;

public class UpdateAfterPushTask extends AsyncTask<String, String, Object>
{
	
	public int iLanguage = 0;
	Typeface arabicFont = null;
	int TIMEOUT_MILLISEC = 10000; // = 10 seconds

	@Override
	protected Object doInBackground(String... arg0)
	{
		// First need to pass login params to the cloud
		// Then the cloud will send a JSON string that has contacts
		// Contacts will have updated ids but also have old ids sent along
		// Find contacts using old ids and update their user ids
		// This will preserve a unique key for all contacts across the app.
		
		String returnThis = "";
		try
		{
			JSONObject json = new JSONObject();
			json.put("user_name", arg0[0]);
			json.put("password", arg0[1]);
			
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			///////////////////////////////////////////////
			//////////// CHANGE WEB SERVICE URL ///////////
			///////////////////////////////////////////////
			String url = "http://softeng.cs.uwosh.edu/students/kiserj66/Web/webservice.php";

			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes(
					"UTF8")));
			request.setHeader("json", json.toString());
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = RestClient.convertStreamToString(instream);
				Log.i("Read from server", result);
				returnThis = result;
			}
		}
		catch (Throwable t)
		{
			returnThis = "Request failed: " + t.toString();
		}
		return returnThis;		
	}
	
	/**
	 * result will be the json string it should have all the contact
	 * info just like the GetFromJsonTask, but it will also have the old user ids stored.
	 * We'll use these old user ids to find and update contacts so that they have
	 * the same id locally as they do on the cloud. 
	 */
	protected void onPostExecute(Object result)
	{
		
	}

}
